﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Waker.Common;
using Waker.APIs.IDCards;
using Waker.Entitys;
using System.IO;
using Waker.APIs.ZKT;
using System.Drawing.Imaging;

namespace Waker.Cards
{
    public partial class FormStaffEdit : Base.FormBasePop
    {
        DataTable _DtSource;
        public FormStaffEdit(string id)
        {
            InitializeComponent();
            this.Text += string.IsNullOrEmpty(id) ? "添加" : "修改";
            _DtSource = new BAL.BAL_Cards().GetEmployeeByID(id);
            this.Load += new EventHandler(FormStaffEdit_Load);
            timerReadIDCard.Enabled = true;
        }

        private void FormStaffEdit_Load(object sender, EventArgs e)
        {
            try
            {
                StartWaiting();
                if (_DtSource.Rows.Count < 1)
                    this.BindingContext[_DtSource].AddNew();
                this.BindingContext[_DtSource].EndCurrentEdit();
                icbEmp_Sex.Properties.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("男", Convert.ToByte(1), -1));
                icbEmp_Sex.Properties.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("女", Convert.ToByte(0), -1));

                var dtEdu = new BAL.BAL_SystemSetting().GetTableByTableName("tbEmp_Education");
                ControlUtil.FillImageComboBox(dtEdu, icbEmp_eduId, "Edu_Name", "Edu_ID");

                var dtBaseDataJob = new BAL.BAL_SystemSetting().GetAllBaseDataByDataType(Enums.BaseDataType.Job);
                ControlUtil.FillImageComboBox(dtBaseDataJob, icbEmp_jobID, "DataName", "ID");


                var dtBaseDataWorkType = new BAL.BAL_SystemSetting().GetAllBaseDataByDataType(Enums.BaseDataType.WorkType);
                ControlUtil.FillImageComboBox(dtBaseDataWorkType, icbWorkType, "DataName", "ID");

                //var dtBaseDataNation = new BAL.BAL_SystemSetting().GetAllBaseDataByDataType(Enums.BaseDataType.Nation); 
                //ControlUtil.FillImageComboBox(dtBaseDataNation, icbEmp_nationId, "DataName", "ID");

                var dtNation = new BAL.BAL_SystemSetting().GetTableByTableName("tbEmp_Nation");
                ControlUtil.FillImageComboBox(dtNation, icbEmp_nationId, "Nation_Name", "Nation_ID");

                var dtSite = new BAL.BAL_Cards().GetAllDepartment();
                ControlUtil.FillImageComboBox(dtSite, icbDept_ID, "Dept_Name", "Dept_ID");
                ControlUtil.BindData(this.Controls, _DtSource);

                if (_DtSource.Rows[0]["Emp_Photo"] != DBNull.Value)
                {
                    var bytes = (byte[])_DtSource.Rows[0]["Emp_Photo"];
                    if (bytes != null && bytes.Length > 0)
                    {
                        var image = new Bitmap(new MemoryStream(bytes));
                        picBoxEmp_Photo.Image = image;
                    }
                }
                if (Session.IDCard_IsConneted)
                {
                    lblIdCardConnected.Text = "已连接";
                    groupIDCard.Text = "身份信息" + "(已连接)";
                }
                else
                {
                    lblIdCardConnected.Text = "未连接";
                    groupIDCard.Text = "身份信息" + "(未连接)";
                }
            }
            catch (Exception ex)
            { UI.ShowError(ex.Message); }
            finally
            { EndWaiting(); }
        }
        protected override void FormSave()
        {
            try
            {
                StartWaiting();
                timerReadIDCard.Enabled = false;
                if (_DtSource == null || _DtSource.Rows.Count < 1)
                    return;
                base.errorPop.ClearErrors();
                if (icbDept_ID.EditValue == null || icbDept_ID.EditValue == DBNull.Value)
                {
                    base.errorPop.SetError(icbDept_ID, "请选择分包商");
                    return;
                }
                //if (string.IsNullOrEmpty(txtEmp_No.Text))
                //{
                //    base.errorPop.SetError(txtEmp_No, "工号不能为空");
                //    return;
                //}
                //if (icbEmp_eduId.EditValue == DBNull.Value || icbEmp_eduId.EditValue == null)
                //{
                //    base.errorPop.SetError(icbEmp_eduId, "请选择学历");
                //    return;
                //}
                //if (icbEmp_jobID.EditValue == DBNull.Value || icbEmp_jobID.EditValue == null)
                //{
                //    base.errorPop.SetError(icbEmp_jobID, "请选择职位");
                //    return;
                //}
                if (string.IsNullOrEmpty(txtEmp_Name.Text))
                {
                    base.errorPop.SetError(txtEmp_Name, "姓名不能为空");
                    return;
                }
                if (icbEmp_Sex.EditValue == DBNull.Value || icbEmp_Sex.EditValue == null)
                {
                    base.errorPop.SetError(icbEmp_Sex, "请选择性别");
                    return;
                }
                //if (icbEmp_nationId.EditValue == DBNull.Value || icbEmp_nationId.EditValue == null)
                //{
                //    base.errorPop.SetError(icbEmp_nationId, "请选择民族");
                //    return;
                //}
                //if (dteEmp_birthdate.EditValue == DBNull.Value || dteEmp_birthdate.EditValue == null)
                //{
                //    base.errorPop.SetError(dteEmp_birthdate, "请选择生日");
                //    return;
                //}
                if (string.IsNullOrEmpty(txtEmp_IDCard.Text) || txtEmp_IDCard.Text.Length != 18)
                {
                    base.errorPop.SetError(txtEmp_IDCard, "身份证号码不能正确");
                    return;
                }

                if (!string.IsNullOrEmpty(txtFingerPwd.Text))
                {
                    int pwd = -1;
                    if (!int.TryParse(txtFingerPwd.Text, out pwd) || pwd < 0)
                    {
                        base.errorPop.SetError(txtFingerPwd, "密码必须为数字,可以为空");
                        return;
                    }
                }
                this.BindingContext[_DtSource].EndCurrentEdit();

                //1.查询工号是否存在
                //2.讲信息上传到指纹机(先判断是否存在)
                //3.讲信息上传到门禁设备(先判断是否存在)
                //4.将上面的上传结果写入到数据中
                //5.保存员工信息到数据库

                //1.查询工号是否存在
                var bal = new BAL.BAL_Cards();
                if (_DtSource.Rows[0]["Emp_ID"] == DBNull.Value)
                {
                    //if (!bal.CheckEMployeeNo(txtEmp_No.Text))
                    //{
                    //    UI.ShowInfo("工号已经存在,请重新输入");
                    //    return;
                    //}
                    if (!bal.CheckEMployeeIDCardNo(txtEmp_IDCard.Text))
                    {
                        UI.ShowInfo("身份证号已经存在,请重新输入");
                        return;
                    }

                    //_DtSource.Rows[0]["Emp_ID"] = Guid.NewGuid().ToString(); 
                }
                var fingerId = 0;
                if (_DtSource.Rows[0]["FingerId"] == DBNull.Value || Convert.ToInt32(_DtSource.Rows[0]["FingerId"]) < 1)
                    fingerId = bal.GetNextFingerId();
                else
                    fingerId = Convert.ToInt32(_DtSource.Rows[0]["FingerId"]);
                //2.讲信息上传到指纹机(先判断是否存在)(无论是否成功都继续)
                //先ping ip 如果存在在连接
                if (IPHelper.TestNetConnected(Session.Finger_IP, 1, 3))
                {
                    if (ZKTHelper.ZKTConnect().IsSuccess)
                    {
                        //if (UI.ShowOKCancel("指纹机未连接,员工数据暂时无法上传到指纹机中.\r\n是否继续?") != DialogResult.OK)
                        //    return; 
                        var res = ZKTHelper.ZKTSetUserInfo(txtEmp_Name.Text, fingerId, txtFingerPwd.Text, 0, true);
                        _DtSource.Rows[0]["IsUploadFinger"] = res.IsSuccess;
                        ZKTHelper.ZKTDisConnect();
                    }
                }
                _DtSource.Rows[0]["FingerId"] = fingerId;

                //3.讲信息上传到门禁设备(先判断是否存在)(无论是否成功都继续)  

                //4.将上面的上传结果写入到数据中

                //5.保存员工信息到数据库
                //_DtSource.Rows[0]["Emp_Photo"] == DBNull.Value &&
                //if (picBoxEmp_Photo.Tag != null && !string.IsNullOrEmpty(picBoxEmp_Photo.Tag.ToString())) 
                //{
                //    var path = picBoxEmp_Photo.Tag.ToString();
                //    if (File.Exists(path))
                //    {
                //        using (BinaryReader reader = new BinaryReader(File.Open(path, FileMode.Open)))
                //        {
                //            var bytes = reader.ReadBytes(Convert.ToInt32(new FileInfo(path).Length));
                //            reader.Close(); ;
                //            _DtSource.Rows[0]["Emp_Photo"] = bytes;
                //        }
                //    }
                //}
                if (picBoxEmp_Photo.Image != null && picBoxEmp_Photo.Tag != null && !string.IsNullOrEmpty(picBoxEmp_Photo.Tag.ToString()))
                {
                    ImageFormat imgformat;
                    switch (picBoxEmp_Photo.Tag.ToString().ToLower())
                    {
                        case ".jpg":
                            imgformat = System.Drawing.Imaging.ImageFormat.Jpeg;
                            break;
                        case ".bmp":
                            imgformat = System.Drawing.Imaging.ImageFormat.Bmp;
                            break;
                        case ".png":
                            imgformat = System.Drawing.Imaging.ImageFormat.Png;
                            break;
                        default:
                            MessageBox.Show("只能存取为: JPG,BMP,PNG 格式");
                            return;
                    }
                    MemoryStream ms = new MemoryStream();
                    picBoxEmp_Photo.Image.Save(ms, imgformat);
                    _DtSource.Rows[0]["Emp_Photo"] = ms.ToArray();
                }
                var isOk = bal.SaveEmployee(_DtSource.Rows[0]);
                EndWaiting();
                if (isOk)
                {
                    UI.ShowInfo("保存成功");
                    Session.ListEmployeeAndCard = bal.GetAllEmployeeAndCard();
                    this.DialogResult = DialogResult.OK;
                }
                else
                {
                    UI.ShowError("保存失败");
                }
            }
            catch (Exception ex)
            { UI.ShowError(ex.Message); }
            finally
            {
                EndWaiting();
                timerReadIDCard.Enabled = true;
            }
        }

        private void timerReadIDCar_Tick(object sender, EventArgs e)
        {
            if (!Session.IDCard_IsConneted)
            {
                return;
            }
            //if (IDCardHelper.ReadCardNo() == txtEmp_IDCard.Text)
            //    return;
            var res = new IDCardHelper().ReadIDCardIfo();
            if (res.IsSuccess)
            {
                if (txtEmp_IDCard.Text == res.ResultData.IDCardNo)
                    return;
                txtEmp_Name.Text = res.ResultData.Name.Trim();
                icbEmp_Sex.EditValue = Convert.ToByte(res.ResultData.Sex);
                icbEmp_nationId.EditValue = Convert.ToInt32(res.ResultData.Nation);
                dteEmp_birthdate.DateTime = new DateTime(
                    Convert.ToInt32(res.ResultData.Born.Substring(0, 4)),
                    Convert.ToInt32(res.ResultData.Born.Substring(4, 2)),
                    Convert.ToInt32(res.ResultData.Born.Substring(6, 2))
                    );
                txtEmp_Address.Text = res.ResultData.Address.Trim();
                txtEmp_IDCard.Text = res.ResultData.IDCardNo;
                using (BinaryReader reader = new BinaryReader(File.Open(res.ResultData.PhotoFileName, FileMode.Open)))
                {
                    var fileInfo = new FileInfo(res.ResultData.PhotoFileName);
                    var bytes = reader.ReadBytes(Convert.ToInt32(fileInfo.Length));
                    reader.Close(); ;
                    var image = new Bitmap(new MemoryStream(bytes));
                    picBoxEmp_Photo.Image = image;
                    //picBoxEmp_Photo.Tag = res.ResultData.PhotoFileName;
                    picBoxEmp_Photo.Tag = fileInfo.Extension;
                }
                //using (FileStream fs = File.OpenRead(res.ResultData.PhotoFileName))
                //{
                //    picBoxEmp_Photo.Image = new Bitmap(fs);
                //    picBoxEmp_Photo.Tag = new FileInfo(res.ResultData.PhotoFileName).Extension;
                //}
                System.Threading.Thread.Sleep(1000);
            }
        }
        protected override void FormClose()
        {
            timerReadIDCard.Enabled = false;
            new IDCardHelper().ClosePort();
            base.FormClose();
            this.Dispose();
        }
        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpLoad_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "JPG图片|*.jpg|BMP图像|*.bmp|PNG图片|*.png";   //指定OpenFileDialog控件打开的文件格式 
            DialogResult dr = openFileDialog1.ShowDialog();
            if (dr != DialogResult.OK)
            {
                return;
            }
            string picpath = openFileDialog1.FileName;
            try
            {
                StartWaiting();
                using (BinaryReader reader = new BinaryReader(File.Open(picpath, FileMode.Open)))
                {
                    var fileInfo = new FileInfo(picpath);
                    var bytes = reader.ReadBytes(Convert.ToInt32(fileInfo.Length));
                    reader.Close(); ;
                    var image = new Bitmap(new MemoryStream(bytes));
                    picBoxEmp_Photo.Image = image;
                    //picBoxEmp_Photo.Tag = picpath;
                    picBoxEmp_Photo.Tag = fileInfo.Extension;
                }
                //using (FileStream fs = File.OpenRead(picpath))
                //{
                //    picBoxEmp_Photo.Image = new Bitmap(fs);
                //    picBoxEmp_Photo.Tag = new FileInfo(picpath).Extension;
                //}
            }
            catch (Exception ex)
            {
                UI.ShowError(ex.Message);
            }
            finally
            {
                EndWaiting();
            }
        }
    }
}
